<template>
    <div class="app-container calendar-list-container">
        <el-form ref="form" :model="form" label-width="90px">
            <el-form-item label="基础设置"></el-form-item>
            <el-form-item label="活动标题" prop="vote_title" :rules="filter_rules({required:true})">
                <el-input clearable style="width: 250px;" placeholder="请输入活动名称" v-model.trim="form.vote_title">
                </el-input>
            </el-form-item>
            <el-form-item label="投票时间" prop="createDate" :rules="filter_rules({required:true})">
                <el-date-picker v-model="form.createDate" type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="投票规则" prop="vote_rule" :rules="filter_rules({required:true})">
                <textarea cols="70" rows="5" style="padding: 10px; border-radius: 5px;" placeholder="请输入投票规则..." v-model.trim="form.vote_rule"></textarea>
            </el-form-item>
            <el-form-item label="活动规则" prop="active_rule" :rules="filter_rules({required:true})">
                <textarea cols="70" rows="5" style="padding: 10px; border-radius: 5px;" placeholder="请输入活动规则..." v-model.trim="form.active_rule"></textarea>
            </el-form-item>
            <el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
                <!-- <el-upload class="avatar-uploader" action="/api/backstage/fileUpload" name="file_path" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <div class="img-box" v-if="form.file_path">
                        <img :src="form.file_path" width="100%" class="avatar">
                    </div>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload> -->
                <div class="img-box" v-if="form.file_path">
                  <img :src="form.file_path" width="100%" class="avatar" @click="sizeSet">
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
            </el-form-item>
            <!-- 选项设置 -->
            <el-form-item label="选项设置"></el-form-item>
            <div class="list-box" v-for="(option,i) in optionList" :key="option.num">
                <section v-if="i == 0">
                    <span style="font-size: 14px;color: #606266;font-weight: bold;margin-left: 33px;">选项一</span>
                    <!-- <el-button size="mini" type="primary" style="margin-left: 71%" @click="openForm(i)">编辑详情</el-button> -->
                </section>
                <section v-else>
                    <i class="iconfont ali-cc-close-square" @click="delRow(i)"></i>
                    <span style="font-size: 14px;color: #606266;font-weight: bold;">{{i | toChinese}}</span>
                    <!-- <el-button size="mini" type="primary" style="margin-left: 71%" @click="openForm(i)">编辑详情</el-button> -->
                </section>
                <br>
                <twoTemp ref="twoTemp"></twoTemp>
            </div>

            <div class="list-button" @click="addOptions">
                <span>添加选项</span>
                <i class="iconfont ali-addnewlist"></i>
            </div>
            <br>

            <!-- 功能设置 -->
            <el-form-item label="功能设置"></el-form-item>

            <el-form-item label="单选多选" prop="select_nums" :rules="filter_rules({required: isShow, type: 'integer'})">
                <el-radio v-model="form.select_method" :label="1" @change="radioChange">单选</el-radio>
                <el-radio v-model="form.select_method" :label="2" @change="radioChange">多选</el-radio>
                <el-input v-show="form.select_method==2" style="width: 200px;margin-left: 20px;" placeholder="请输入限制的数量" v-model.number="form.select_nums"></el-input>
            </el-form-item>

            <el-form-item label="参与人数限制" label-width="100px"></el-form-item>
            <el-form-item label="组织选择">
                <el-tag v-for="dept in rangeForm.depts" :key="dept.id" style="margin-right:6px;">{{dept.label}}</el-tag>
                <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('dept')"></el-button>
            </el-form-item>
            <el-form-item label="小组选择">
                <el-tag v-for="group in rangeForm.groups" :key="group.id" style="margin-right:6px;">{{group.group_name}}</el-tag>
                <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('group')"></el-button>
            </el-form-item>

        </el-form>

        <!-- 部门 和小组 组件 -->
        <section>
            <dept-transfer ref="deptInit" @closeTransfer="transfer.deptShow = false" @getDepts="getDepts" :isShow="transfer.deptShow"></dept-transfer>
            <group-transfer ref="groupInit" @closeTransfer="transfer.groupShow = false" @getGroups="getGroups" :isShow="transfer.groupShow"></group-transfer>
        </section>
        <section>
          <size-temp ref="size" :img.sync="form.file_path" title="图片设置"></size-temp>
        </section>
    </div>
</template>
<script>
import twoTemp from "./twoTemp";
import { toSimplifiedChinese } from "@/utils";
import { mapGetters } from "vuex";
import dept_transfer from "@/views/activity/components/add_dept_transfer";
import group_transfer from "@/views/activity/components/add_group_transfer";
import sizeTemp from '@/components/draggableSize'

export default {
  name: "typeTwo",
  components: {
    twoTemp: twoTemp,
    "dept-transfer": dept_transfer,
    "group-transfer": group_transfer,
    sizeTemp
  },
  computed: {
    ...mapGetters(["vtDecide", "vtIsSub"])
  },
  data() {
    return {
      form: { file_path: "", select_method: 1 },
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      rangeForm: { depts: [], groups: [] },
      optionList: [{ num: 1 }], //选项
      transfer: { deptShow: false, groupShow: false },
      isShow: false
    };
  },
  watch: {
    async vtDecide() {
      if (this.vtDecide == "add") {
        await this.clearForm();
      }
    }
  },
  filters: {
    toChinese(index) {
      return "选项" + toSimplifiedChinese(++index);
    }
  },
  methods: {
    sizeSet(){
      this.$refs.size.open()
    },
    radioChange(e) {
      this.isShow = e === 2 ? true : false;
    },
    openForm(index) {
      //编辑详情 打开子模版模态
      this.$refs.twoTemp[index].openForm();
    },
    async clearForm() {
      this.form = { file_path: "", select_method: 1 };
      this.rangeForm = { depts: [], groups: [] };
      this.optionList = [{ num: 1 }];
      this.$refs.twoTemp[0].clearForm();
      this.$refs.deptInit.clear();
      this.$refs.groupInit.clear();
    },
    addOptions() {
      //添加选项
      this.optionList.push({ num: this.optionList.length + 1 });
    },
    delRow(index) {
      this.optionList.splice(index, 1);
    },
    openDeptModal(e) {
      //打开穿梭框组件
      if (e == "dept") {
        this.transfer.deptShow = true;
      } else {
        this.transfer.groupShow = true;
      }
    },
    getGroups(e) {
      //获取小组
      if (e.length == 0) {
        this.$message.warning("至少要选择一个小组");
        return;
      }
      this.rangeForm.groups = e;
      this.transfer.groupShow = false;
    },
    getDepts(e) {
      //获取部门
      if (e.length == 0) {
        this.$message.warning("至少要选择一个部门");
        return;
      }
      this.rangeForm.depts = e;
      this.transfer.deptShow = false;
    },
    async twoTempValidate(e) {
      //多模板 校验
      for (let i = 0; i < this.optionList.length; i++) {
        await this.$refs[e][i].validate();
      }
      if (this.vtIsSub) {
        let result = this.optionList.map((item, i) => {
          return this.$refs[e][i].form;
        });
        this.form.voteOptions = JSON.stringify(result);
      }
    },
    async validate() {
      //表单校验
      await this.twoTempValidate("twoTemp");
      try {
        await this.$refs["form"].validate();
      } catch (flag) {
        //falg 此处为 false全局 vtIsSub = false
        await this.$store.dispatch("SetIsSub", false);
      }
      if (this.vtIsSub) {
        return await this.submit();
      }
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if (
        name[name.length - 1] === "jpg" ||
        name[name.length - 1] === "jpeg" ||
        name[name.length - 1] === "png"
      ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    async submit() {
      /**
       * "voteRanges":[{"range_type":"范围类型(1为部门/2为小组/3为人员)","organization_id":"组织架构id"}],
       */
      if (
        this.rangeForm.groups.length == 0 &&
        this.rangeForm.depts.length == 0
      ) {
        this.$message.warning("请选择参与人数限制");
        return;
      }
      let voteRanges;
      if (this.rangeForm.groups) {
        voteRanges = this.rangeForm.groups.map(item => {
          if (item.ids) {
            return { range_type: 2, organization_id: item.ids, id: item.id };
          } else {
            return { range_type: 2, organization_id: item.id };
          }
        });
      }
      if (this.rangeForm.depts) {
        voteRanges = this.rangeForm.depts.map(item => {
          if (item.ids) {
            return { range_type: 1, organization_id: item.ids, id: item.id };
          } else {
            return { range_type: 1, organization_id: item.id };
          }
        });
      }
      if (this.rangeForm.groups && this.rangeForm.depts) {
        let groups = this.rangeForm.groups.map(item => {
          if (item.ids) {
            return { range_type: 2, organization_id: item.ids, id: item.id };
          } else {
            return { range_type: 2, organization_id: item.id };
          }
        });
        let depts = this.rangeForm.depts.map(item => {
          if (item.ids) {
            return { range_type: 1, organization_id: item.ids, id: item.id };
          } else {
            return { range_type: 1, organization_id: item.id };
          }
        });
        voteRanges = groups.concat(depts);
      }
      //格式化 时间 "vote_starttime":"开始时间","vote_endtime":"结束时间"
      let date = {
        vote_starttime: this.form.createDate[0] + " 00:00:00",
        vote_endtime: this.form.createDate[1] + " 23:59:59"
      };
      return {...this.form, voteRanges: JSON.stringify(voteRanges), ...date}
    },
    async initList(e, range) {
      let form_date = {createDate: [ this.formateDate(e.vote_starttime), this.formateDate(e.vote_endtime)]}
      this.form = {...e, ...form_date}
      this.optionList = e.voteOptions.map((_, i) => {
        return { num: i + 1 };
      });
      for (let i = 0; i < e.voteOptions.length; i++) {
        let el = e.voteOptions[i];
        await this.$refs.twoTemp[i].setForm(el);
      }
      this.rangeForm = range;
    },
    formateDate(e) {
      return e ? e.split(" ")[0]: '';
    }
  }
};
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
.list-button {
  padding-bottom: 10px;
  text-align: center;
  .ali-addnewlist {
    font-size: 25px;
  }
  &:hover {
    cursor: pointer;
  }
}

.list-box {
  border-bottom: 1px solid #e4e7ed;
  padding-top: 10px;
  .ali-cc-close-square {
    color: #f56c6c;
    margin-left: 10px;
    font-size: 20px;
    &:hover {
      cursor: pointer;
    }
  }
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>

